<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax post请求验证用户名是否可用</title>
</head>
<body>
<script type="text/javascript">
    window.onload = function (){
        //获得焦点，不显示
        document.getElementById("username").onfocus = function (){
            document.getElementById("tipMsg").innerHTML=""
        }
        //失去焦点（显示用户名是否可用），与数据库中的数据进行比较
       document.getElementById("username").onblur = function (){
           // console.log("正在发送ajax请求验证用户名")
           // 发送ajax post请求
           //1.创建ajax核心对象
           var xhr = new XMLHttpRequest()
           //2.注册回调函数
           xhr.onreadystatechange = function (){
               if (this.readyState == 4) {
                   if (this.status == 200) {
                        document.getElementById("tipMsg").innerHTML = this.responseText
                   }else{
                       alert(this.status)
                   }
               }
           }
           //3.开启通道
           xhr.open("POST","/ajax02/check",true)
           //4.发送请求
           xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
           //获取表单数据
           var username = document.getElementById("username").value;
           xhr.send("uname="+username)
       }
    }
</script>
用户名：<input type="text" id="username">
<span id="tipMsg"></span>
<!--<form enctype="application/x-www-form-urlencoded"></form>-->
</body>
</html>